package com.huizhan.web.controller;

import java.io.*;
import java.util.*;

import javax.servlet.http.*;
import org.jdom2.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.*;

import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.view.*;

@Api(tags = "Pay",description = "支付")
@Controller
public class PayController {
    
    @Autowired
    private ProjectDao dao;
   
    @Autowired
    private OrderFormDao tdao;
   
    @Autowired
    private TicketDao ticketDao;

    /**
     * 接收微信支付成功通知
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/api/pay/notify", method = RequestMethod.POST)
    public void getnotify(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
                
        PrintWriter writer = response.getWriter();
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        
        Map<String, String> map = null;
        try {
            map = XMLUtil.doXMLParse(result);
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        // 若支付成功，则告知微信服务器收到通知
        if (map.get("return_code").equals("SUCCESS")) {
            if (map.get("result_code").equals("SUCCESS")) {
                
                String wechatPayGuid=  map.get("out_trade_no");
                String openid=  map.get("openid");
                OrderForm orderForm = tdao.findByWechatPayGuidAndOpenId(wechatPayGuid, openid);
                if(orderForm!=null&&orderForm.getIsPay()==0){

                    orderForm.setIsPay(Long.parseLong("1"));
                    tdao.save(orderForm);
                    
                    Optional<Project> project= dao.findById(orderForm.getProjectId());
                    if(project.isPresent()){
                        List<Ticket> list=new ArrayList<Ticket>();
                        List<Ticket> tickets= ticketDao.findByTicketTypeId(orderForm.getTicketTypeId());
                        for (Integer i=0;i<orderForm.getCount();i++) {
                            Ticket ticket=new Ticket();
                            getCode(ticket, tickets);
                            ticket.setIdNumber(UUID.randomUUID().toString());
                            ticket.setCreateDate(new Date()); 
                            ticket.setProjectId(orderForm.getProjectId());
                            ticket.setTicketTypeId(orderForm.getTicketTypeId());
                            ticket.setIsPassage(0);
                            ticket.setName(orderForm.getPhone());
                            ticket.setOrderItemId(orderForm.getOrderFormId());
                            tickets.add(ticket);
                            list.add(ticket);
                        }
                        ticketDao.saveAll(list);
                        SendSMS(project.get(),orderForm,list,request);
                        String notifyStr = XMLUtil.setXML("SUCCESS", "");
                        writer.write(notifyStr);
                        writer.flush();
                    }
                }
            }
        }
    }
    
    private Boolean SendSMS(Project project,OrderForm orderForm,List<Ticket> list,HttpServletRequest request){

        boolean b=false;

        try {
            String data="{\"account\":\"dh81653\",\"password\":\""+
            TenpayUtil.MD5("e3YiG73c").toLowerCase()
            +"\",\"msgid\":\""
            +(UUID.randomUUID().toString())
            +"\",\"phones\":"
            +orderForm.getPhone()
            +",\"content\":\""
            +orderForm.getName()
            +"您收到"
            +project.getName()
            +"电子票"
            +(orderForm.getCount())
            +"张 ";

            for (Ticket ticket : list) {
                data+=request.getScheme() + "://" + request.getServerName()+"/"+ticket.getTicketTypeId()+","+ticket.getCode()+"\\n";
            }

            data+="\",\"sign\":\"【"+project.getSignName()+"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

            TenpayHttpClient httpClient = new TenpayHttpClient();  

            httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
            String  resContent = httpClient.getResContent();

            if(resContent.contains("提交成功")){
                b=true;
            }
        } catch (Exception e) {
             b=false;
        }
       return b;
    }
    
    /**
     * 获取码值
     * @param ticket
     */
    private void getCode(Ticket ticket,List<Ticket> list){
        String no=TenpayUtil.random(6);
        for (Ticket ticket2 : list) {
            if(ticket2.getCode().equals(no)){
                getCode(ticket,list);
            }
        }
        ticket.setCode(no);
    }
}